import ast
import datetime
import json
from django.http import JsonResponse
import yaml
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from kubernetes import config, client

# Create your views here.
# 读取 Kubernetes 配置文件
config.load_kube_config()

# 创建 Kubernetes 的 API 客户端
v1 = client.AppsV1Api()


@csrf_exempt
def deployment_create(request):
    if request.method == 'POST':
        deployment_name = request.POST.get('deployment_name')  # deployment名称
        deployment_image = request.POST.get('image')  # 容器镜像
        deployment_port = request.POST.get('container_port')
        # 获取环境变量列表
        env_vars1 = request.POST.getlist('env_vars1')  # 环境变量
        env_vars2 = request.POST.getlist('env_vars2')  # 环境变量值
        try:
            # 创建 Deployment 的配置
            deployment = {
                "apiVersion": "apps/v1",
                "kind": "Deployment",
                "metadata": {
                    "name": deployment_name,
                    "labels": {
                        "app": deployment_name
                    }
                },
                "spec": {
                    "replicas": 3,
                    "selector": {
                        "matchLabels": {
                            "app": deployment_name
                        }
                    },
                    "template": {
                        "metadata": {
                            "labels": {
                                "app": deployment_name
                            }
                        },
                        "spec": {
                            "containers": [
                                {
                                    "name": deployment_name,
                                    "image": deployment_image,
                                    "ports": [
                                        {
                                            "containerPort": int(deployment_port)
                                        }
                                    ],
                                    "env": []

                                }
                            ]
                        }
                    }
                }
            }
            # 为 Deployment 的 Pod 模板添加环境变量
            for i in range(len(env_vars1)):
                deployment['spec']['template']['spec']['containers'][0]['env'].append(
                    {"name": env_vars1[i], "value": env_vars2[i]}
                )
            # 创建 Deployment
            api_response = v1.create_namespaced_deployment(body=deployment, namespace="default")
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '创建 Deployment 失败'})
        return JsonResponse({'status': 200, 'msg': '创建 Deployment 成功'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
        pass


@csrf_exempt
def deployment_ls(request):
    if request.method == 'GET':
        try:
            # 获取 Deployment 列表
            deployment_list = []
            api_response = v1.list_namespaced_deployment(namespace="default")
            for item in api_response.items:
                dic = {
                    "deployment_name": item.metadata.name,
                    "deployment_image": item.spec.template.spec.containers[0].image,
                    "deployment_port": item.spec.template.spec.containers[0].ports[0].container_port,
                    "deployment_replicas": item.spec.replicas,
                    "deployment_status": item.status.conditions[0].type,
                    "deployment_create_time": item.metadata.creation_timestamp.strftime("%Y-%m-%d %H:%M:%S")
                }
                deployment_list.append(dic)
            return JsonResponse({'status': 200, 'msg': '获取 Deployment 列表成功', 'data': deployment_list})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '获取 Deployment 列表失败'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass


@csrf_exempt
def deployment_rm(request):
    if request.method == 'POST':
        try:
            # 获取 POST 请求的参数
            deployment_name = request.POST.get('deployment_name')
            # 创建 Kubernetes 的 API 客户端
            api_instance = client.AppsV1Api()
            # 删除指定命名空间中的特定 Deployment
            api_response = api_instance.delete_namespaced_deployment(
                name=deployment_name,
                namespace="default",
                body=client.V1DeleteOptions(propagation_policy='Foreground')
            )
            return JsonResponse({'status': 200, 'msg': '删除 Deployment 成功'})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '删除 Deployment 失败'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})


@csrf_exempt
def deployment_pause(request):
    if request.method == 'POST':
        namespace = 'default'
        deployment_name = request.POST.get('deployment_name')
        try:
            api_instance = client.AppsV1Api()
            deployment = api_instance.read_namespaced_deployment(name=deployment_name, namespace=namespace)
            deployment.spec.replicas = 0
            api_instance.patch_namespaced_deployment(
                name=deployment_name,
                namespace=namespace,
                body=deployment
            )
            return JsonResponse({'status': 'success', 'message': 'Deployment 暂停成功'})
        except Exception as e:
            print(e)
            print("Deployment 暂停失败:")
            return JsonResponse({'status': 'fail', 'message': 'Deployment 暂停失败'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})


@csrf_exempt
def deployment_start(request):
    if request.method == 'POST':
        namespace = 'default'
        deployment_name = request.POST.get('deployment_name')
        try:
            api_instance = client.AppsV1Api()
            deployment = api_instance.read_namespaced_deployment(name=deployment_name, namespace="default")
            # 修改 Deployment 的 replicas 数量为原始值
            deployment.spec.replicas = 3
            api_instance.patch_namespaced_deployment(
                name=deployment_name,
                namespace=namespace,
                body=deployment
            )
            return JsonResponse({'status': 'success', 'message': 'Deployment 重新启动成功'})
        except Exception as e:
            print(e)
            print("Deployment 重新启动失败:")
            return JsonResponse({'status': 'fail', 'message': 'Deployment 重新启动失败'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})


@csrf_exempt
def update_deployment_image(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'fail', 'message': '只允许使用 POST 请求更新 Deployment 镜像'})
    namespace = 'default'
    deployment_name = request.POST.get('deployment_name')
    new_image = request.POST.get('new_image')
    try:
        api_instance = client.AppsV1Api()
        deployment = api_instance.read_namespaced_deployment(name=deployment_name, namespace=namespace)
        # 更新 Deployment 的每个容器的镜像
        for container in deployment.spec.template.spec.containers:
            container.image = new_image
        api_instance.patch_namespaced_deployment(
            name=deployment_name,
            namespace=namespace,
            body=deployment
        )
        return JsonResponse({'status': 'success', 'message': 'Deployment 镜像更新成功'})
    except Exception as e:
        print("Deployment 镜像更新失败:", str(e))
        return JsonResponse({'status': 'fail', 'message': 'Deployment 镜像更新失败'})


@csrf_exempt
def expose_deployment_with_nodeport(request):
    if request.method == 'POST':
        # 获取 POST 请求的参数
        deployment_name = request.POST.get('deployment_name')
        node_port = request.POST.get('node_port')
        try:
            # 读取 Deployment 的配置
            api_instance = client.AppsV1Api()
            deployment = api_instance.read_namespaced_deployment(name=deployment_name, namespace="default")
            # 创建 Service 的配置
            service = {
                "apiVersion": "v1",
                "kind": "Service",
                "metadata": {
                    "name": f"{deployment_name}-service"
                },
                "spec": {
                    "type": "NodePort",
                    "ports": [
                        {
                            "port": deployment.spec.template.spec.containers[0].ports[0].container_port,
                            "targetPort": deployment.spec.template.spec.containers[0].ports[0].container_port,
                            "nodePort": int(node_port)
                        }
                    ],
                    "selector": {
                        "app": deployment_name  # 根据 Deployment 的标签选择器进行匹配
                    }
                }
            }
            # 创建 Service
            api_instance = client.CoreV1Api()
            service = api_instance.create_namespaced_service(namespace="default", body=service)
            service_ip = service.spec.cluster_ip
            service_port = service.spec.ports[0].node_port
            return JsonResponse({'status': 'success', 'message': 'Deployment 暴露成功',
                                 'data': {'service_ip': service_ip, 'service_port': service_port}})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 'fail', 'message': 'Deployment 暴露失败'})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass
